<template>
  <el-form :rules="rules" ref="myForm" :model="form">
    <div class="modle banner" v-show="show">
      <div class="tit">
        <b>轮播图</b>
        <span>共（{{ form.bannerInfo.length }}/3）张</span>
      </div>
      <p class="info">1.最多放三张轮播图</p>
      <p class="info">2.建议尺寸690*260每张/使用本地图片时,≤4M</p>
      <div class="bannerinfo" v-for="(item, index) in form.bannerInfo" :key="index">
        <div class="content">
          <div class="content_left flex-column">
            <el-image class="img" :src="item.img" fit="fill"></el-image>
            <div class="upload flex-center">
              <div class="btn flex-center" @click="changeUploadType(index)">
                更换
              </div>
            </div>
          </div>
          <div class="content_right">
            <p>跳转内容：</p>
            <div class="linkTo">
              <el-form-item
                :prop="`bannerInfo.${index}.jump_type`"
                :rules="rules.jump_type"
              >
                <el-input
                  class="jump"
                  placeholder="请输入内容"
                  readonly
                  :value="item.jump_value"
                >
                  <el-select
                    slot="append"
                    value=""
                    placeholder="请选择"
                    @change="changeJump($event, index)"
                  >
                    <el-option
                      v-for="item in jump_options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-input>
              </el-form-item>
              <el-form-item
                :prop="`bannerInfo.${index}.goods_id`"
                :rules="rules.goods_id"
                v-if="item.jump_type == 1"
              >
                <div
                  class="goods flex-btw"
                  @click="selectGoods(item.goods_id, index)"
                >
                  <span>{{ item.name ? item.name : "请选择商品" }}</span>
                  <i class="el-icon-plus"></i>
                </div>
              </el-form-item>
              <el-form-item
                :prop="`bannerInfo.${index}.category_id`"
                :rules="rules.category_id"
                v-if="item.jump_type == 3"
              >
                <el-select
                  v-model="item.category_id"
                  placeholder="请选择"
                  class="classify"
                >
                  <el-option
                    v-for="item in category"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                :prop="`bannerInfo.${index}.category_id`"
                :rules="rules.category_id"
                v-if="item.jump_type == 4"
              >
                <el-cascader
                  class="classify"
                  v-model="item.category_id"
                  :options="category"
                  :props="{
                    expandTrigger: 'hover',
                    value: 'id',
                    label: 'title',
                    children: 'selfNext',
                  }"
                >
                </el-cascader>
              </el-form-item>
            </div>
          </div>
        </div>
        <div class="operation">
          <div class="delete" @click="handDelete(index)">
            <img
              src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2405/21/Hd7tNvIYGGYiscscsB9FkNlzSeVsV5rpcV2bRKdx.png"
              alt=""
            />
          </div>
          <div class="move flex-column-between">
            <img
              v-show="index != 0"
              @click="Move(index, 'up')"
              src="@/assets/images/shop_up.png"
            />
            <img
              v-show="index != form.bannerInfo.length - 1"
              @click="Move(index, 'down')"
              src="@/assets/images/shop_down.png"
            />
          </div>
        </div>
      </div>
      <div
        class="add flex-middle"
        v-if="form.bannerInfo.length < 3"
        @click="changeUploadType()"
      >
        <div class="add-content">
          <p>+新增一条图片广告</p>
          <p>(建议尺寸690*260每张/使用本地图片时，≤4M)</p>
        </div>
      </div>
      <div class="flex-center">
        <el-button class="submit flex-center" v-repeatClick="1000" @click="submit()"
          >保存</el-button
        >
      </div>
    </div>
  </el-form>
</template>

<script>
import { packApi } from "@/utils/public";
import { poster_save, poster_index } from "@/api/shop/shop";
export default {
  props: ["show", "puzzleImg", "upload_img", "uploadHeader", "category"],
  data() {
    return {
      form:{
        bannerInfo: [], // { goods_id:'',name:'',img:'',subimg:'',ordid:0,}
      },
      upload_inedx: "",
      jump_options: [
        {
          value: "1",
          label: "推荐商品",
        },
        {
          value: "2",
          label: "积分商城",
        },
        {
          value: "3",
          label: "一级分类",
        },
        {
          value: "4",
          label: "二级分类",
        },
        {
          value: "5",
          label: "仅展示",
        },
      ], // 跳转内容下拉框
      rules: {
        jump_type: [
          { required: true, message: "请选择跳转内容", trigger: "blur" },
        ],
        goods_id: [{ required: true, message: "请选择商品", trigger: "blur" }],
        category_id: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.listLoading = true;
    this.getList();
  },
  methods: {
    // 保存
    submit() {
      this.$refs.myForm.validate((valid) => {
        if (valid) {
          this.listLoading = true;
          let data = this.form.bannerInfo.map((item, index) => {
            return {
              img: item.subimg,
              goods_id: item.goods_id,
              ordid: index + 1,
              jump_type: item.jump_type,
              category_id: Array.isArray(item.category_id) ? item.category_id[1] : item.category_id,
            };
          });
          data = JSON.stringify(data);
          let params = packApi({ list: data });
          poster_save(params).then((res) => {
            this.listLoading = false;
            if (res.errcode == 0) {
              this.$message.success("保存成功");
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }else{
          // this.message.error("")
        }
      });
    },
    // 获取列表
    getList() {
      let params = packApi();
      poster_index(params).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.form.bannerInfo = res.data.list.map((item) => {
            // 查找与选择值相匹配的跳转选项对象
            const info = this.jump_options.find(
              (option) => option.value == item.jump_type
            );
            return {
              goods_id: item.goods_id,
              name: item.goods_name,
              img: item.img_dispaly,
              subimg: item.img,
              category_id: item.category_id,
              jump_type: item.jump_type,
              jump_value: info ? info.label : "",
            };
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //打开父组件的选择商品弹窗
    selectGoods(id, index) {
      let radio = true;
      this.$emit("selectGoods", {
        id,
        index,
        ref: "refBanner",
        isRadio: radio,
      });
    },
    //获取到父组件传过来的商品id，name
    getSelectedGood(index, info) {
      if (info.name) {
        this.form.bannerInfo[index].name = info.name;
        this.form.bannerInfo[index].goods_id = info.id;
      }
    },
    uploadSuccess(res, index) {
      if (JSON.stringify(index)) {
        this.form.bannerInfo[index].subimg = res.data.path; //上传的路径
        this.form.bannerInfo[index].img = res.data.src; //显示的路径
      } else {
        this.form.bannerInfo.push({
          subimg: res.data.path,
          img: res.data.src,
          name: "",
          goods_id: "",
          jump_type: "1",
          jump_value: "推荐商品",
        });
      }
    },
    uploadErr() {
      this.$message.error("上传失败，请重试");
    },
    // 打开父组件的图片上传方式
    changeUploadType(index) {
      this.upload_inedx = "";
      if (index !== "") {
        this.upload_inedx = index;
      }
      this.$emit("changeUploadType", {
        pid: 1,
        ref: "refBanner",
      });
    },
    // 获取父级返回的图片信息
    getUploadImg(res) {
      let index = this.upload_inedx;
      this.uploadSuccess(res, index);
    },
    //移动排序
    Move(index, type) {
      // 检查传入的索引是否在有效范围内
      if (index < 0 || index >= this.form.bannerInfo.length) {
        throw new Error("Invalid index");
      }
      // 根据移动类型计算目标索引
      let toIndex = type === "up" ? index - 1 : index + 1;
      // 再次检查目标索引是否在有效范围内
      if (toIndex < 0 || toIndex >= this.form.bannerInfo.length) {
        throw new Error("Cannot move element out of bounds");
      }
      // 使用解构赋值和展开语法来移动元素
      const [item] = this.form.bannerInfo.splice(index, 1);
      // 在目标位置插入移除的元素
      this.form.bannerInfo.splice(toIndex, 0, item);
    },
    // 删除
    handDelete(index) {
      this.$confirm("是否删除该内容", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.form.bannerInfo.splice(index, 1);
        this.$message.success("删除成功");
      });
    },
    // 选择跳转内容
    changeJump(e, index) {
      if(e==this.form.bannerInfo[index].jump_type){
        return
      }
      // 查找与选择值相匹配的跳转选项对象
      const info = this.jump_options.find((option) => option.value == e);
      this.$set(this.form.bannerInfo[index], "jump_value", info.label);
      this.$set(this.form.bannerInfo[index], "jump_type", e);
      this.$set(this.form.bannerInfo[index], "category_id", "");
      this.$set(this.form.bannerInfo[index], "name", "");
      this.$set(this.form.bannerInfo[index], "goods_id", "");
      this.$refs.myForm.clearValidate()
    },
  },
};
</script>

<style lang="scss" scoped>
.banner {
  width: 750px;
  .info {
    margin-top: 3px;
  }
  .bannerinfo {
    margin-top: 17px;
    display: flex;
  }
  .content {
    background: white;
    width: 595px;
    padding: 15px 20px;
    box-sizing: border-box;
    display: flex;
    .content_left {
      .img {
        width: 292px;
        height: 110px;
      }
      .btn {
        padding: 6px 28px;
        color: #19b098;
        border: 1px solid #19b098;
        margin-top: 10px;
        border-radius: 4px;
        cursor: pointer;
      }
    }
    .content_right {
      color: #616161;
      font-size: 14px;
      margin-left: 20px;
    }
    .linkTo {
      margin-top: 10px;
      .jump /deep/.el-input__inner {
        cursor: pointer !important;
        text-align: center !important;
      }
      .goods {
        background-color: #e1f3f0;
        border: 1px solid #19b098;
        width: 100%;
        height: 35px;
        border-radius: 4px;
        padding: 0 15px;
        box-sizing: border-box;
        margin-top: 10px;
      }
      .classify {
        width: 100%;
        margin-top: 10px;
        /deep/.el-input {
          width: 100%;
        }
      }
    }
  }
  .operation {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 20px;
    img {
      width: 20px;
      height: 20px;
    }
    .move {
      img:nth-child(2) {
        margin-top: 10px;
      }
    }
  }
  .add {
    width: 595px;
    height: 112px;
    background: #fff;
    margin-top: 15px;
    position: relative;
    box-sizing: border-box;
    cursor: pointer;
    &-content {
      width: 100%;
      text-align: center;
      p:nth-child(1) {
        font-weight: bold;
        font-size: 14px;
        color: #03a98e;
      }
      p:nth-child(2) {
        font-size: 13px;
        color: #999999;
        margin-top: 5px;
      }
    }
  }
}
.submit {
  cursor: pointer;
}

/deep/.el-input-group__append {
  min-width: 90px;
  background-color: #ffffff;
}

/deep/ .el-form-item{
  margin-bottom: 0;
}
</style>